<template>
  <Row class="box-padding1">
    <Col span="4"
         class="col-height100 tree-style">
    <Tree :data="tree"
          @on-select-change="getProPersonList"></Tree>
    </Col>
    <Col span="20"
         class="col-main"
         style="padding: 15px">

    <!-- <div v-if="showAllButton"> -->
    <div v-if="true">
      <Button type="primary"
              style="margin-right: 5px"
              @click="clickButton('add', '')"
              v-if='isTop && control.addOrg'>新增项目部</Button>
      <Button type="primary"
              style="margin-right: 5px"
              @click="clickButtonWork('add', '')"
              v-if='(isTopForWorkOrDep || canEdit) && beTeam && control.addWork && isNotDep'>新增工区</Button>
      <Button type="primary"
              style="margin-right: 5px"
              @click="clickButtonDep('add', '')"
              v-if='(isTopForWorkOrDep || canEdit) && beTeam && control.addDep'>新增部门</Button>
    </div>
    <Table border
           :columns="columns"
           :data="list"
           style="margin: 20px 0">
      <template slot-scope="{ row }"
                slot="name">
        <span>{{row.shortName || row.name}}</span>
      </template>
      <template slot-scope="{ row }"
                slot="type">
        <span v-if="row.type == '2'">项目部</span>
        <span v-if="row.type == '3'">工区</span>
        <span v-if="row.type == '6'">项目部部门</span>
        <span v-if="row.type == '7'">工区部门</span>
      </template>
      <template slot-scope="{ row }"
                slot="action">
        <div>
          <span class='button-class'
                @click="clickButton('edit', row)"
                v-show='row.type == 2 && row.canBeEdit && control.edit'>编辑</span>
          <span class='button-class'
                @click="clickButton('details',row)"
                v-show='row.type == 2 && control.detail'>详情</span>
          <span class='button-class'
                @click="clickButtonWork('edit', row)"
                v-show='row.type == 3 && row.canBeEdit && control.edit'>编辑</span>
          <span class='button-class'
                @click="clickButtonWork('details',row)"
                v-show='row.type == 3 && control.detail'>详情</span>
          <span class='button-class'
                @click="clickButtonDep('edit', row)"
                v-show='(row.type == 6 || row.type == 7) && row.canBeEdit && control.edit'>编辑</span>
          <span class='button-class'
                @click="clickButtonDep('details',row)"
                v-show='(row.type == 6 || row.type == 7) && control.detail'>详情</span>
          <span class='button-class'
                @click="deleteData(row)"
                v-show='row.canBeEdit && control.delete'>删除</span>
        </div>

      </template>
    </Table>
    <Page show-elevator
          show-sizer
          show-total
          @on-change="currentChange"
          @on-page-size-change="pageChange"
          :current="page.current"
          :page-size="page.pageSize"
          :total="page.total"
          :page-size-opts="this.page.opts"
          class="pagination"
          style="text-align: center" />
    </Col>
  </Row>
</template>

<script>
import { getUserInLocalstorage, getTreeInLocalstorage } from '@/libs/util'
import { mapState, mapActions } from 'vuex'
export default {
  name: 'project-team',
  data() {
    return {
      columns: [
        {
          title: '序号',
          align: 'center',
          width: 90,
          render: (h, params) => {
            return h(
              'span',
              params.index + (this.page.current - 1) * this.page.pageSize + 1
            )
          }
        },
        {
          title: '名称',
          slot: 'name',
          align: 'center'
        },
        {
          title: '类型',
          slot: 'type',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          width: 180,
          align: 'center'
        }
      ],
      list: [], //列表数据
      tree: [], //左侧树数据
      page: {
        total: 0,
        current: 1,
        pageSize: 10,
        opts: [10, 20, 50, 100]
      },
      treeActive: {},
      treeList1: [],
      checkTreeProId: '',
      canEdit: true, //点击树判断新增权限
      beTeam: true, //是否工区项目用户
      isTop: true, //是否为顶级
      isTopForWorkOrDep: false, //用来判断顶级时展示工区与部门
      userInfo: {},
      control: {},
      topId: '', //储存最上一级id
      isNotDep: true, //点击部门时不能建工区
      showAllButton: true
    }
  },
  mounted() {
    this.buttonShow()
    this.getTree()
  },
  activated() {
    //console.log(this.node)
    let children = []
    if (this.node.mode && this.treeActive.objectId) {
      if (this.node.mode == 'add') {
        this.treeActive.children.push(this.node)
      } else {
        let temp
        this.treeActive.children.forEach((item, index) => {
          if (item.id == this.node.id) {
            temp = index
            this.node.expand = true
            if (item.children && item.children.length > 0) {
              this.node.children = JSON.parse(JSON.stringify(item.children))
            }
          }
        })

        this.treeActive.children.splice(temp, 1, this.node)
      }
      this.getNode({})
    }
    this.getList(this.treeActive.objectId)
  },
  computed: mapState({
    node: state => state.projectTree.node //获取vuex里项目树的state
  }),
  methods: {
    ...mapActions(['getNode']),
    //获取项目部门树
    getTree() {
      this.$api.ProjectPerson.getOrgTree().then(res => {
        if (res.code === 200) {
          this.tree = res.data
          res.data.forEach(item => {
            let o = {
              objectId: item.objectId,
              parentId: item.parentId,
              linkedId: item.linkedId,
              type: item.type
            }
            this.treeList1.push(o)
            //item.title = item.shortName

            if (item.children.length > 0) {
              item.children = this.getCheildItem(item.children)
            }
          })
          this.topId = res.data[0].id

          this.treeActive = res.data[0]
          this.getList(this.treeActive.objectId) //这里是获取缓存里树的数据或者初始化
          //判断按钮权限
          this.userInfo = getUserInLocalstorage()

          if (this.userInfo.userType == 'ADMIN_USER') {
            //只有管理员身份才有新增按钮的权限
            this.showAllButton = true
          } else {
            this.showAllButton = false
          }
          if (this.userInfo.userInOrgType == 'PROJECT_TEAM_USER') {
            this.beTeam = true //为项目工区用户
          } else {
            this.beTeam = false
          }
          let userTeamId = this.userInfo.projectTeamId

          this.isTop = true
          if (this.treeActive.type == 2) {
            this.isTopForWorkOrDep = true
          } else {
            this.isTopForWorkOrDep = false
          }
        }
      })
    },
    //递归树状结构
    getCheildItem(data) {
      let item = data

      const arr = []
      item.forEach(val => {
        let o = {
          objectId: val.objectId,
          parentId: val.parentId,
          type: val.type,
          linkedId: val.linkedId,
          id: val.id
        }
        this.treeList1.push(o)
        let obj = {}
        obj.title = val.title
        obj.parentId = val.parentId
        obj.objectId = val.objectId
        obj.linkedId = val.linkedId
        obj.id = val.id
        obj.type = val.type
        obj.children = []
        obj.name = val.name
        obj.expand = true
        obj.shortName = val.shortName
        if (val.children.length > 0) {
          obj.children = this.getCheildItem(val.children)
        }
        arr.push(obj)
      })
      return arr
    },
    getProPersonList(data) {
      this.treeActive = data[0]
      if (this.topId != data[0].id) {
        //判断是否为最上一级
        this.isTop = false
        this.isTopForWorkOrDep = false
      } else {
        this.isTop = true
        this.isTopForWorkOrDep = true
      }
      if (this.treeActive.type == 6 || this.treeActive.type == 7) {
        //如果是部门不能建工区
        this.isNotDep = false
      } else {
        this.isNotDep = true
      }

      this.checkTreeProId = ''
      if (this.treeActive.type == 2) {
        this.canEdit = false
      } else {
        this.getParent(data[0].parentId)
      }

      this.getList(this.treeActive.objectId)
    },
    //循环查询父级
    getParent(id) {
      if (id) {
        for (var i = 0; i < this.treeList1.length; i++) {
          let item = this.treeList1[i]
          if (item.objectId == id) {
            if (item.type == 2) {
              let userTeamId = this.userInfo.projectTeamId
              this.checkTreeProId = item.objectId
              if (!userTeamId) {
                this.canEdit = false
              } else if (userTeamId == this.checkTreeProId) {
                this.canEdit = true
              } else {
                this.canEdit = false
              }
              return
            } else {
              this.getParent(item.parentId)
            }
          }
        }
      }
    },
    getList(id) {
      if (id) {
        let reqData = {
          currentPage: this.page.current,
          pageSize: this.page.pageSize,

          whereMap: {
            parentId: id,
            types: [2, 3, 6, 7]
          }
        }
        this.$api.ProjectTeam.findList(reqData)
          .then(res => {
            this.list = res.data.resultObject
            this.page.total = res.data.totalRecord
          })
          .catch(error => {
            this.$Message.error(res.message)
          })
      }
    },
    currentChange(current) {
      //翻页
      this.page.current = current
      this.getList(this.treeActive.objectId)
    },
    pageChange(pagesize) {
      //改变页数
      this.page.pageSize = pagesize
      this.getList(this.treeActive.objectId)
    },
    clickButton(type, row) {
      //项目
      if (type != 'details') {
        let pageData = {
          whereMap: this.whereMap || {},
          page: this.page
        }
      }
      const addId = parseInt(Math.random() * 100000)
      let route = {
        params: {
          type,
          id: type == 'add' ? this.treeActive.objectId : row.id,
          enterpriseShortName: this.treeActive.shortName,
          enterpriseName: this.treeActive.title,
          typeObj: this.treeActive.type,
          enterpriseId: this.treeActive.objectId, //树的id
          objectId: row.objectId || '', //自己的id

          name:
            type == 'add'
              ? '机构新增'
              : type == 'edit'
              ? '机构编辑'
              : '机构详情'
        },
        name:
          type == 'add'
            ? 'project-team-org-add'
            : type == 'edit'
            ? 'project-team-org-edit'
            : 'project-team-org-detail'
      }
      this.$router.push(route)
    },
    clickButtonWork(type, row) {
      //工区
      if (type != 'details') {
        let pageData = {
          whereMap: this.whereMap || {},
          page: this.page
        }
      }
      const addId = parseInt(Math.random() * 100000)
      let route = {
        params: {
          type,
          id: type == 'add' ? this.treeActive.objectId : row.id,
          objectId: row.objectId || '',
          typeObj: this.treeActive.type,
          enterpriseName: this.treeActive.shortName || this.treeActive.name,
          enterpriseId: this.treeActive.objectId,
          linkedId: this.treeActive.linkedId,
          name:
            type == 'add'
              ? '新增工区'
              : type == 'edit'
              ? '编辑工区'
              : '工区详情'
        },
        name:
          type == 'add'
            ? 'project-team-work-add'
            : type == 'edit'
            ? 'project-team-work-edit'
            : 'project-team-work-detail'
      }
      this.$router.push(route)
    },
    clickButtonDep(type, row) {
      //部门
      if (type != 'details') {
        let pageData = {
          whereMap: this.whereMap || {},
          page: this.page
        }
      }
      const addId = parseInt(Math.random() * 100000)
      let route = {
        params: {
          type,
          id: type == 'add' ? this.treeActive.objectId : row.id,
          objectId: row.objectId || '',
          typeObj: this.treeActive.type,
          enterpriseName: this.treeActive.shortName || this.treeActive.name,
          enterpriseId: this.treeActive.objectId,
          name:
            type == 'add'
              ? '新增部门'
              : type == 'edit'
              ? '编辑部门'
              : '部门详情'
        },
        name:
          type == 'add'
            ? 'project-team-dep-add'
            : type == 'edit'
            ? 'project-team-dep-edit'
            : 'project-team-dep-detail'
      }
      this.$router.push(route)
    },
    deleteData(row) {
      this.$Modal.confirm({
        title: '温馨提示',
        closable: true,
        content: '确认删除吗？',
        width: 360,
        onOk: () => {
          if (row.type == 2) {
            //项目部删除
            this.$api.ProjectTeam.getDetail(row.objectId).then(resp => {
              if (resp.code == 200) {
                let params = resp.data
                this.$api.ProjectTeam.orgDelete(params).then(resp => {
                  if (resp.code == 200) {
                    this.$Message.success('删除成功')
                    this.treeActive.children.forEach((item, index) => {
                      if (row.id == item.id) {
                        this.treeActive.children.splice(index, 1)
                      }
                    })
                    this.getList(this.treeActive.objectId)
                  } else {
                    this.$Message.warning(resp.message)
                  }
                })
              } else {
                this.$Message.warning(resp.message)
              }
            })
          } else if (row.type == 3) {
            //工区删除
            this.$api.ProjectTeam.workDetail(row.objectId).then(resp => {
              if (resp.code == 200) {
                let params = resp.data
                this.$api.ProjectTeam.workDelete(params).then(resp => {
                  if (resp.code == 200) {
                    this.$Message.success('删除成功')
                    this.treeActive.children.forEach((item, index) => {
                      if (row.id == item.id) {
                        this.treeActive.children.splice(index, 1)
                      }
                    })
                    this.getList(this.treeActive.objectId)
                  } else {
                    this.$Message.warning(resp.message)
                  }
                })
              } else {
                this.$Message.warning(resp.message)
              }
            })
          } else {
            //部门删除
            //工区删除
            this.$api.ProjectTeam.depDetail(row.objectId).then(resp => {
              if (resp.code == 200) {
                let params = resp.data
                this.$api.ProjectTeam.depDelete(params).then(resp => {
                  if (resp.code == 200) {
                    this.$Message.success('删除成功')
                    this.treeActive.children.forEach((item, index) => {
                      if (row.id == item.id) {
                        this.treeActive.children.splice(index, 1)
                      }
                    })
                    this.getList(this.treeActive.objectId)
                  } else {
                    this.$Message.warning(resp.message)
                  }
                })
              } else {
                this.$Message.warning(resp.message)
              }
            })
          }
        }
      })
    },
    //按钮权限
    buttonShow() {
      let buttonList = JSON.parse(localStorage.getItem('buttonList'))
      buttonList.map(val => {
        let key = Object.keys(val).toString()
        if (key === this.$route.name) {
          Object.values(val)[0].map(item => {
            if (item.code == 'P_0202_01') {
              this.control.addOrg = true
            } else if (item.code == 'P_0202_02') {
              this.control.addWork = true
            } else if (item.code == 'P_0202_03') {
              this.control.addDep = true
            } else if (item.code == 'P_0202_04') {
              this.control.edit = true
            } else if (item.code == 'P_0202_05') {
              this.control.delete = true
            } else if (item.code == 'P_0202_06') {
              this.control.detail = true
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.box-padding1 {
  height: 100%;
}
.tree-style {
  overflow: auto;
  height: 100% !important;
  border-right: 1px solid #ccc;
  padding: 15px;
}
</style>
